package isec.amov.tp2.automaintenance;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class EditDistance extends Activity {

	private DBAdapter db;
	private int pos, id;
	private double newDistance=0,correntDistance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_distance);
		

		Bundle bundle = this.getIntent().getExtras();
		pos = bundle.getInt("id");

		db = new DBAdapter(this);
		db.open(this);

		Carro obj = db.getCarro(pos);
		id = obj.getId();
		correntDistance= obj.getQuilometros();
		Log.i("ola:", ""+id+":"+pos);

	}

	public void onUpdateDistance(View v) {

		AlertDialog.Builder bdialog;
		Carro obj=db.getCarro(pos);

		EditText newDist = (EditText) findViewById(R.id.editDistance);
		if(newDist.getText().toString().length()==0){
			newDistance=0;
		}
		else{
			newDistance = Double.parseDouble(newDist.getText().toString());
		}
		bdialog = new AlertDialog.Builder(this);
		if (!checkValues(newDistance)) {
			bdialog.setTitle(R.string.error);
			bdialog.setMessage(R.string.errorDistance);
			bdialog.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			AlertDialog dialog = bdialog.create();
			dialog.show();

		}
		else{
			Calendar calendar = GregorianCalendar.getInstance();
			//obj.setDia(calendar.get(GregorianCalendar.DAY_OF_MONTH););
			//obj.setMes(calendar.get(GregorianCalendar.MONTH););
			//obj.setAno(calendar.get(GregorianCalendar.YEAR););
			obj.setQuilometros(newDistance);
			
			bdialog.setTitle(R.string.sucess);
			bdialog.setMessage(R.string.sucessAlterado);
			bdialog.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							
							finish();
						}
					});
			AlertDialog dialog = bdialog.create();
			dialog.show();
		}
		//actualizar BD
		db.updateCarro(obj, pos);
		db.close();
	}
	public void onCancel(View v){
		db.close();
		finish();
	}
	public boolean checkValues(double newDistance) {

		if (newDistance<=correntDistance) {
			return false;
		}
		return true;

	}

}
